package com.dpwgc.demo.service;

import com.dpwgc.demo.mapper.*;
import com.dpwgc.demo.model.*;
import com.dpwgc.demo.utils.DateUtil;
import com.dpwgc.demo.utils.RedisUtil;
import com.dpwgc.demo.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * 用户相关操作
 */
@Service
public class UserService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    AdminMapper adminMapper;

    @Autowired
    UserGroupMapper userGroupMapper;

    @Autowired
    MessageMapper messageMapper;

    @Autowired
    GroupMapper groupMapper;

    @Autowired
    DateUtil dateUtil;

    @Autowired
    RedisUtil redisUtil;

    /**
     * 登录
     * @param phone 用户手机号码
     * @param password 用户密码
     * @return
     */
    public ResultUtil<Object> loginService(String phone,String password){

        ResultUtil<Object> resultUtil = new ResultUtil<>();

        //安全加密类
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();

        if(password.length()<6 || password.length()>20){

            resultUtil.setCode(100);
            resultUtil.setMsg("密码格式违规");
            resultUtil.setData("");
            return resultUtil;
        }

        User user = new User();

        try {
            /**
             * 根据根据手机号码查找用户
             */
            user = userMapper.queryUserByPhone(phone);

            //手机号不存在
            if(user == null){

                resultUtil.setCode(100);
                resultUtil.setMsg("手机号码不存在");
                return resultUtil;
            }
            //手机号存在
            else {

                //密码解密，匹配
                if(encoder.matches(password,user.getPassword())){

                    /* 生成token,并将token存储于redis中，设置7200s过期时间 */
                    String token = UUID.randomUUID().toString().replaceAll("-", "");
                    redisUtil.set(user.getId()+"", token,7200);

                    resultUtil.setCode(200);
                    resultUtil.setMsg("登录成功|token:"+token);
                    resultUtil.setData(user);
                    return resultUtil;
                }
            }
            resultUtil.setCode(100);
            resultUtil.setMsg("密码错误");
            resultUtil.setData("");
            return resultUtil;

        }catch (Exception e){

            resultUtil.setCode(100);
            resultUtil.setMsg("登录失败");
            resultUtil.setData("");
            return resultUtil;
        }
    }

    /**
     * 注册
     * @param phone 用户手机号码
     * @param nickname 用户昵称
     * @param password 用户密码
     * @param headImg 用户头像
     * @return
     */
    public ResultUtil<Object> insertUserService(String phone,String nickname,String password,String headImg){

        ResultUtil<Object> resultUtil = new ResultUtil<>();

        if(password.length()<6 || password.length()>20){
            resultUtil.setCode(100);
            resultUtil.setMsg("密码格式违规");
            resultUtil.setData("");
            return resultUtil;
        }
        if(nickname.length()<1 || nickname.length()>10){
            resultUtil.setCode(100);
            resultUtil.setMsg("昵称格式违规");
            resultUtil.setData("");
            return resultUtil;
        }
        if(phone.length()<6 || phone.length()>16){
            resultUtil.setCode(100);
            resultUtil.setMsg("手机号码格式违规");
            resultUtil.setData("");
            return resultUtil;
        }

        //验证用户手机号码是否被注册
        User u = userMapper.queryUserByPhone(phone);
        if(u != null){
            resultUtil.setCode(100);
            resultUtil.setMsg("手机号已被注册");
            resultUtil.setData("");
            return resultUtil;
        }

        //安全加密类
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();

        User user = new User();
        user.setPhone(phone);
        user.setNickname(nickname);
        user.setPassword(encoder.encode(password));//对用户密码进行加密
        user.setHeadImg(headImg);
        user.setStatus(1);
        user.setCreateTime(dateUtil.getDateTime());
        user.setUpdateTime(dateUtil.getDateTime());

        userMapper.insert(user);

        resultUtil.setCode(200);
        resultUtil.setMsg("注册成功");
        resultUtil.setData(user.getId());
        return resultUtil;
    }

    /**
     * 根据用户id返回用户信息
     * @param id 用户id
     * @return
     */
    public ResultUtil<Object> queryUserByIdService(int id){

        ResultUtil<Object> resultUtil = new ResultUtil<>();

        User user = userMapper.selectById(id);
        user.setPassword(null);

        resultUtil.setCode(200);
        resultUtil.setMsg("操作成功");
        resultUtil.setData(user);
        return resultUtil;
    }

    /**
     * 根据用户id修改用户个人信息
     * @param id 用户id
     * @return
     */
    public ResultUtil<Object> updateUserByIdService(int id,String phone,String nickname,String headImg){

        ResultUtil<Object> resultUtil = new ResultUtil<>();

        User u = userMapper.selectById(id);

        User user = new User();

        user.setId(id);
        user.setPhone(phone);
        user.setNickname(nickname);
        user.setHeadImg(headImg);

        user.setStatus(u.getStatus());
        user.setCreateTime(u.getCreateTime());
        user.setPassword(u.getPassword());
        user.setUpdateTime(dateUtil.getDateTime());

        int i = userMapper.updateById(user);

        resultUtil.setCode(200);
        resultUtil.setMsg("操作成功");
        resultUtil.setData(i);
        return resultUtil;
    }

    /**
     * 用户申请加入群组
     * @param userId 用户id
     * @param groupId 群组id
     * @return
     */
    public ResultUtil<Object> userApplyGroupService(int userId,int groupId){

        ResultUtil<Object> resultUtil = new ResultUtil<>();

        UserGroup userGroup = new UserGroup();
        userGroup.setUserId(userId);
        userGroup.setGroupId(groupId);
        userGroup.setStatus(2);
        userGroup.setCreateTime(dateUtil.getDateTime());
        userGroup.setUpdateTime(dateUtil.getDateTime());

        //检查用户是否申请加入该群聊
        UserGroup ug = userGroupMapper.checkUserGroup(userId,groupId);

        if(ug == null){
            int i = userGroupMapper.insert(userGroup);

            resultUtil.setCode(200);
            resultUtil.setMsg("操作成功");
            resultUtil.setData(userGroup);
            return resultUtil;
        }
        if(ug.getStatus() == 1){

            resultUtil.setCode(100);
            resultUtil.setMsg("已加入群组");
            resultUtil.setData("");
            return resultUtil;
        }
        else {
            resultUtil.setCode(100);
            resultUtil.setMsg("已提交申请");
            resultUtil.setData("");
            return resultUtil;
        }
    }

    /**
     * 用户退出群组
     * @param userId 用户id
     * @param groupId 群组id
     * @return
     */
    public ResultUtil<Object> userExitGroupService(int userId,int groupId){

        ResultUtil<Object> resultUtil = new ResultUtil<>();

        Admin admin = adminMapper.checkAdminLv(userId, groupId);
        //不是管理员
        if(admin == null){

            UserGroup userGroup = new UserGroup();
            userGroup.setUserId(userId);
            userGroup.setGroupId(groupId);
            userGroup.setUpdateTime(dateUtil.getDateTime());

            int i = userGroupMapper.userExitGroup(userGroup);

            resultUtil.setCode(200);
            resultUtil.setMsg("操作成功");
            resultUtil.setData(i);
            return resultUtil;
        }
        else {
            //群主or管理员
            switch (admin.getLv()){

                //如果是群主
                case 1:

                    resultUtil.setCode(100);
                    resultUtil.setMsg("请先转移群主权限再退出");
                    return resultUtil;

                //如果是管理员
                case 2:

                    //删除管理员权限
                    int i = adminMapper.deleteAdmin(userId, groupId);

                    UserGroup userGroup = new UserGroup();
                    userGroup.setUserId(userId);
                    userGroup.setGroupId(groupId);
                    userGroup.setUpdateTime(dateUtil.getDateTime());

                    //退出群组
                    int i1 = userGroupMapper.userExitGroup(userGroup);

                    resultUtil.setCode(200);
                    resultUtil.setMsg("操作成功");
                    resultUtil.setData(i);
                    return resultUtil;

                default:
                    resultUtil.setCode(100);
                    resultUtil.setMsg("操作失败");
                    return resultUtil;
            }
        }
    }
}
